import time
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 1. 创建浏览器驱动对象，设置隐式等待和窗口最大化
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)

try:
    driver.get("http://localhost:82/")
    driver.find_element(By.PARTIAL_LINK_TEXT, "登录").click()
    driver.find_element(By.ID, "username").send_keys("13800138006")
    driver.find_element(By.ID, "password").send_keys("123456")
    driver.find_element(By.ID, "verify_code").send_keys("8888")
    driver.find_element(By.CLASS_NAME, "J-login-submit").click()
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, "a[href='/index.php/Home/Index/index.html']").click()
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, "#q").send_keys("小米")
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR,
                        "img[data-original='/public/upload/goods/thumb/5/goods_thumb_5_0_236_236.png']").click()
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, "#join_cart").click()
    time.sleep(1)
    # # 5. 获取加入购物车弹出提示信息
    # 等待iframe出现并切换到该iframe
    driver.switch_to.frame(1)
    element = driver.find_element(By.CSS_SELECTOR, "body > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > table:nth-child(3) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > span:nth-child(1)")
    text = element.text
    print(text)
    time.sleep(1)
    # # 6. 刷新页面
    # 点击ctrl+R刷新
    driver.refresh()
    time.sleep(1)
    # # # 7. 查看当前页面购物车中的商品信息
    cart_icon = driver.find_element(By.CSS_SELECTOR, "body > div:nth-child(4) > div:nth-child(2) > div:nth-child(3) > a:nth-child(1) > div:nth-child(1) > span:nth-child(2)")
    cart_icon.click()
    time.sleep(2)
    # 检查购物车是否为空
    try:
        # 尝试查找空购物车提示信息
        empty_cart_msg = driver.find_element(By.CLASS_NAME, "no-carts")
        print(f"购物车为空，提示信息: {empty_cart_msg.text}")
    except:
        # 购物车不为空，获取商品件数和总价
        try:
            # 获取商品件数
            goods_count = driver.find_element(By.CSS_SELECTOR, "#goods_num").text
            # 获取总价
            total_price = driver.find_element(By.CSS_SELECTOR, "#total_fee").text
            print(f"购物车中有 {goods_count} 件商品，总价为: {total_price}")
        except Exception as e:
            print(f"获取购物车信息时出错: {e}")

finally:
    # 关闭浏览器
    driver.quit()